//
//  HTSearchResultView.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/7.
//

import SwiftUI
import AppLovinSDK
import Refresh

struct HTSearchResultView: View {

  @Binding var var_type: String

  @EnvironmentObject private var var_store: HTAppStore
  @State var var_searchText: String = ""
  @State private var var_curSubscribe: HTSubscribe?
  @State private var var_showMRECAdView: Bool = true
  @State private var var_selAnime: HTAnime = HTAnime()
  @State private var var_showPushToVideoDetail: Bool = false
  @State private var var_searchAnimes: [HTAnime] = []
  @State private var var_showRefresh = false
  @State private var var_isRefresh = false
  @State private var var_isMore = false
  @State private var var_isNoMore = false
  @State private var var_page = 1
  @State private var var_page_size = 10
  @State private var var_headerRefreshing: Bool = false
  @State private var var_footerRefreshing: Bool = false
  @State private var var_noMore: Bool = false
  
  var body: some View {
    VStack{
        // 跳转播放详情页面
      NavigationLink(destination: HTVideoDetailScreen(var_id: var_selAnime.var_id, var_source: "4"), isActive: $var_showPushToVideoDetail) {
        EmptyView()
      }

      VStack{
        ScrollView {
            // 下拉刷新
          RefreshHeader(refreshing: $var_headerRefreshing, action: {
            self.ht_loadData()
          }) { progress in
            HTActivityIndicator(var_style: .medium)
          }

          // 列表内容
          VStack(spacing: 10){
            ForEach(0..<var_searchAnimes.count, id: \.self) { index in
              let var_count = var_searchAnimes.count
              let var_searchAnime = var_searchAnimes[index]
              Button{
                var_selAnime = var_searchAnime
                var_showPushToVideoDetail = true
                HTNetworkManager().ht_requestForBuried(.htEnumSearchResultClNew(var_kid: "1", var_item_id: var_searchAnime.var_id, var_type: var_type, var_word: var_searchText))
              } label: {
                HTSearchResultCell(var_type: $var_type, var_searchText: $var_searchText, var_searchAnime: var_searchAnime)
              }
                .cornerRadius(8)
              if (var_count > 3 && index == 2 && var_showMRECAdView && var_curSubscribe == nil) {
                VStack{
                  HTMRECAdView(var_onDisappear:  {
                    var_showMRECAdView = false
                  })
                }
              }
              if (var_count <= 3 && (index == var_count - 1) && var_showMRECAdView) {
                VStack{
                  HTMRECAdView(var_onDisappear:  {
                    var_showMRECAdView = false
                  })
                }
              }
            }
          }
          .padding(.horizontal, 15)
          .padding(.top, 10)

          if var_searchAnimes.count > 0 {
            RefreshFooter(refreshing: $var_footerRefreshing, action: {
              self.ht_loadMore()
            }) {
              if var_noMore {
                Text("No more data !")
                  .foregroundColor(.secondary)
                  .padding()
              } else {
                HTActivityIndicator(var_style: .medium)
                  .padding()
              }
            }
            .noMore(var_noMore)
            .preload(offset: 50)
          }
        }
        .enableRefresh()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
      }
      .frame(maxWidth: .infinity, maxHeight: .infinity)

      if (var_curSubscribe == nil) {
        HTBannerAd()
          .frame(width: UIDevice.ht_screenWidth(), height: (UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50)
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(Color(hex: "#f5f5f5"))
    .onAppear{
      var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
      if (var_searchAnimes.count == 0) {
        ht_loadData()
      }
    }
    .onReceive(var_store.objectWillChange) { _ in
      var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
    }
  }

  private func ht_loadData() {
    var_page = 1
    var_searchAnimes = []
    var_store.dispatch(HTEnumSearchAction.ht_searchList(params: ["keyword": var_searchText, "page": "\(var_page)", "page_size": "\(var_page_size)"], andCallback: { var_result in
      var_searchAnimes = var_result ?? []
      var_headerRefreshing = false
      var_noMore = false
      var_showMRECAdView = true
      HTNetworkManager().ht_requestForBuried(.htEnumSearchResultShNew(var_type: var_type, var_result: "1", var_keyword: var_searchText))
    }))
  }

  private func ht_loadMore() {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
      var_page += 1
      var_store.dispatch(HTEnumSearchAction.ht_searchList(params: ["keyword": var_searchText, "page": "\(var_page)", "page_size": "\(var_page_size)"], andCallback: { var_result in
        var_footerRefreshing = false
        if (var_result != nil && var_result!.count == 0) {
          var_noMore = true
        } else {
          var_noMore = false
          var_searchAnimes = var_searchAnimes + (var_result ?? [])
        }
      }))
    }
  }
}
